package com.hanbang.taitaigou.utils.db;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.animation.Animation;

import com.hanbang.taitaigou.model.DbGwcData;
import com.hanbang.taitaigou.model.GoodListData;
import com.hanbang.taitaigou.ui.widget.CircleImageView;
import com.hanbang.taitaigou.utils.ui.LogUtils;
import com.hanbang.taitaigou.utils.ui.ToastUtils;

import org.json.JSONException;
import org.json.JSONStringer;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.db.table.DbModel;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.List;

/**
 * Created by Administrator on 2016/3/23.
 */
public class GwcDbUtil {
    public static String GWC_CHANG = "GWC_CHANG";
    public static String GWC_CHANG_CLEAR = "GWC_CHANG_CLEAR";
    public static String GWC_CHANG_ADD = "GWC_CHANG_ADD";
    public static String GWC_CHANG_SUB = "GWC_CHANG_SUB";
    public static String GWC_CHANG_DATA = "GWC_CHANG_DATA";

    public static String SELECTNUMBER = "selectNumber";
    public static String GOODID = "id";

    public static String DELETE_DB = "DELETE_DB";
    /**
     * 市场价
     */
    public static String ORIGINAL_PRICE = "originalPrice";
    /**
     * 零售价
     */
    public static String SELL_PRICE = "sellPrice";

    /**
     * 商品加入数据库
     *
     * @return 是否加入成功
     */
    public static boolean addGood(DbGwcData dbGwcData) {
        try {
            //判断库存
            if (dbGwcData.isAddKucun()) {
                DbUtil.getDbUtils().saveOrUpdate(dbGwcData);
                Intent intent = new Intent(GWC_CHANG_ADD);
                intent.putExtra(GWC_CHANG_DATA,dbGwcData);
                x.app().sendBroadcast(intent);
                return true;
            } else {
                ToastUtils.showShort(x.app(), "库存不足");
                return false;
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 商品加入数据库---->自动+1
     *
     * @return 是否加入成功
     */
    public static boolean addGoodAutoNumber(DbGwcData dbGwcData) {
        try {
            int selectNumber = 1;
            DbGwcData old = DbUtil.getDbUtils().findById(DbGwcData.class, dbGwcData.getId());
            if (old != null) {
                selectNumber = old.getSelectNumber() + 1;
            }
            dbGwcData.setSelectNumber(selectNumber);
            return addGood(dbGwcData);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 商品减少数据库
     *
     * @return 是否成功
     */
    public static boolean subGood(DbGwcData dbGwcData) {
        try {
            if (dbGwcData.getSelectNumber() <= 0) {
                //减少为0，那么就把数据删除了
                DbUtil.getDbUtils().delete(dbGwcData);
            } else {
                //选择的数量不为0，那么就更新
                DbUtil.getDbUtils().saveOrUpdate(dbGwcData);
            }
            Intent intent = new Intent(GWC_CHANG_SUB);
            intent.putExtra(GWC_CHANG_DATA,dbGwcData);
            x.app().sendBroadcast(intent);
            return true;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 商品加入数据库---->自动-1
     *
     * @return 是否成功
     */
    public static boolean subGoodAutoNumber(DbGwcData dbGwcData) {
        try {
            int selectNumber = 0;
            //先查询是否有
            DbGwcData old = DbUtil.getDbUtils().findById(DbGwcData.class, dbGwcData.getId());
            if (old != null) {
                selectNumber = old.getSelectNumber() - 1;
            } else {
                return false;
            }
            dbGwcData.setSelectNumber(selectNumber);
            return subGood(dbGwcData);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 设置实体类里面的选择数目为数据库的数目
     */
    public static void setDataDbSelectNumber(GoodListData dataDbSelectNumber) {
        dataDbSelectNumber.setNumber(getGwcIdNumber(dataDbSelectNumber.getId()));
        upDataDbData(dataDbSelectNumber);
    }

    public static void setDataDbSelectNumber(List<GoodListData> datas) {
        for (GoodListData d : datas) {
            setDataDbSelectNumber(d);
        }
    }

    /**
     * 更新数据库的数据
     */
    public static void upDataDbData(GoodListData dataDbSelectNumber) {
        try {
            DbUtil.getDbUtils().saveOrUpdate(dataDbSelectNumber.getDbGwcData());

            Intent intent = new Intent(GWC_CHANG);
            intent.putExtra("GWC_CHANG_DATA", dataDbSelectNumber);
            // intent.getSerializableExtra("data");
            x.app().sendBroadcast(intent);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取购物车数据
     */
    public static List<DbGwcData> getDbGoods() {
        try {
            int del = DbUtil.getDbUtils().delete(DbGwcData.class, WhereBuilder.b(SELECTNUMBER, "<=", 0));
            LogUtils.e("delete and SELECTNUMBER <= 0", del + "");
            return DbUtil.getDbUtils().findAll(DbGwcData.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取数据库的购物车信息已json返回
     * {"goods_id":1,"quantity":10}
     *
     * @return null表示没有数据
     */
    public static String getGwcToJson() {
        //获取购物车数据库的商品id与数量
        JSONStringer goodsJson = new JSONStringer();
        List<DbModel> data = null;
        try {
            data = DbUtil.getDbUtils().selector(DbGwcData.class).select(GOODID, SELECTNUMBER).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
        if (data == null || data.size() == 0) {
            //没有商品
            //显示没有商品的ImageView
            return null;
        }
        try {
            goodsJson.array();
            for (DbModel d : data) {
                goodsJson.object();
                goodsJson.key("goods_id");
                goodsJson.value(d.getInt(GOODID));
                goodsJson.key("quantity");
                goodsJson.value(d.getInt(SELECTNUMBER));
                goodsJson.endObject();
            }
            goodsJson.endArray();
            return goodsJson.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //没有商品
        return null;
    }

    /**
     * 获取购物车商品的种类的总数 ----->商品种类，不管选择的数量
     */
    public static long getGwcAllGoodType() {
        long number = 0;
        try {
            number = DbUtil.getDbUtils().selector(DbGwcData.class).count();
        } catch (DbException e) {
            e.printStackTrace();
        }
        return number;
    }

    /**
     * 获取数据库购物车数量的总数 -----商全部品选择的数目
     */
    public static int getGwcAllNumber() {
        int number = 0;
        try {
            List<DbModel> dbModels = DbUtil.getDbUtils().selector(DbGwcData.class).select(SELECTNUMBER).findAll();
            if (dbModels == null) {
                return number;
            }
            for (DbModel d : dbModels) {
                try {
                    number += d.getInt(SELECTNUMBER);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return number;
    }

    /**
     * 获取购物车指定商品id的数量
     */
    public static int getGwcIdNumber(int id) {
        //获得选择的个数
        int numberS = 0;
        try {
            DbModel dd = DbUtil.getDbUtils().selector(DbGwcData.class).where(GOODID, "=", id).select(SELECTNUMBER).findFirst();
            if (dd != null) {
                numberS = dd.getInt(SELECTNUMBER);
            }
            if (dd != null) {
                dd = null;
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return numberS;
    }

    /**
     * 获取数据库购物车  指定的 价格总数
     * 顶部有类型
     *
     * @param moneyType 那种价格
     * @see #ORIGINAL_PRICE
     * @see #SELL_PRICE
     *
     */
    public static double getGwcAlltMoney(String moneyType) {
        double number = 0;
        try {
            List<DbModel> dbModels = DbUtil.getDbUtils().selector(DbGwcData.class).select(moneyType, SELECTNUMBER).findAll();
            if (dbModels == null) {
                return number;
            }
            for (DbModel d : dbModels) {
                try {
                    number += d.getDouble(moneyType) * d.getInt(SELECTNUMBER);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
            if (dbModels != null) {
                dbModels.clear();
                dbModels = null;
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return number;
    }

    /**
     * 获取 购物车市场价的总额
     */
    public static double getGwcAlltOriginalMoney() {
        return getGwcAlltMoney(ORIGINAL_PRICE);
    }

    /**
     * 获取 购物车零售价的总额
     */
    public static double getGwcAlltRetailMoney() {
        return getGwcAlltMoney(SELL_PRICE);
    }


    /**
     * 根据id获取数据库购物车价格总数
     * * @param moneyType  那种价格
     *
     * @see #ORIGINAL_PRICE
     * #RETAIL_PRICE
     */
    public static double getGwcIdMoney(int id, String moneyType) {
        double number = 0;
        try {
            DbModel dbModels = DbUtil.getDbUtils().selector(DbGwcData.class).where(GOODID, "=", id).select(moneyType, SELECTNUMBER).findFirst();
            if (dbModels == null) {
                return number;
            }
            try {
                number += dbModels.getDouble(moneyType) * dbModels.getInt(SELECTNUMBER);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (dbModels != null) {
                dbModels = null;
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return number;
    }

    /**
     * 获取 指定id 购物车市场价的总额
     */
    public static double getGwcIdAlltOriginalMoney(int id) {
        return getGwcIdMoney(id, ORIGINAL_PRICE);
    }

    /**
     * 获取 指定id 购物车零售价的总额
     */
    public static double getGwcIdAlltSellMoney(int id) {
        return getGwcIdMoney(id, SELL_PRICE);
    }

    /**
     * 删除购物车中的某一个商品
     */
    public static boolean  delete(DbGwcData dbGwcData){
        //先查询是否有
        int selectNumber = 0;
        try {
            DbGwcData old = DbUtil.getDbUtils().findById(DbGwcData.class, dbGwcData.getId()); if (old != null) {
                selectNumber = old.getSelectNumber() - old.getSelectNumber();
            } else {
                return false;
            }
            dbGwcData.setSelectNumber(selectNumber);
            return deleteGood(dbGwcData);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }
    public static boolean deleteGood(DbGwcData dbGwcData) {
        try {
            if (dbGwcData.getSelectNumber() <= 0) {
                //减少为0，那么就把数据删除了
                DbUtil.getDbUtils().delete(dbGwcData);
            } else {
                //选择的数量不为0，那么就更新
                DbUtil.getDbUtils().saveOrUpdate(dbGwcData);
            }
            Intent intent = new Intent(DELETE_DB);
            intent.putExtra(GWC_CHANG_DATA,dbGwcData);
            x.app().sendBroadcast(intent);
            return true;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 清空购物车
     */
    public static void clearAllGwc() {
        try {
            DbUtil.getDbUtils().delete(DbGwcData.class);
            x.app().sendBroadcast(new Intent(GWC_CHANG_CLEAR));
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    /**
     * 加入购物车动画,, 未写完
     */
    public static void addGouwucheAnimtion(Drawable drawable, View startView, View endView,
                                           int duration, Animation.AnimationListener animationListener) {
        int[] startLocation = new int[2];
        int[] endtLocation = new int[2];
        startView.getLocationInWindow(startLocation);
        endView.getLocationInWindow(endtLocation);
        CircleImageView iview = new CircleImageView(startView.getContext());
        iview.setImageDrawable(drawable);
    }



}
